using UnityEngine;
using UnityEngine.AI;

public class Tree : ActorBase
{
    public Vector3 Pos;
    private int _count;
    public void SetCount(int value)
    {
        _count = value;
    }
    protected override void OnStart()
    {
        this.GameObject.transform.position = Pos;
        base.OnStart();
        var agent = this.GameObject.GetComponent<NavMeshAgent>();
        if (agent != null)
        {
            agent.obstacleAvoidanceType = ObstacleAvoidanceType.NoObstacleAvoidance;
            agent.Warp(Pos);
        }else
        {
           
        }
    }
    public override Vector3 GetWorldPosition()
    {
        if (this.IsGameObjectEnabled)
        {
            return this.GameObject.transform.position;
        }
        return Pos;
    }
    public override ActorType GetActorType()
    {
        return ActorType.Tree;
    }
    private bool _playing;
    public void Action()
    {
        if (_playing) return;
        _count--;
        this.Enabled = _count > 0;
        _playing = true;
        GameEntry.Coroutine.Start(action1());
    }
    private System.Collections.IEnumerator action1()
    {
        var time = 1f;
        while (time > 0f)
        {
            var sinv = Mathf.Sin(time * Mathf.PI * 2f);
            time -= Time.deltaTime * 6f;
            var q = Quaternion.Euler(0, 0, sinv * 5f);
            GameObject.transform.rotation = q;
            yield return null;
        }
        GameObject.transform.rotation = Quaternion.identity;
        _playing = false;
        var res = GameEntry.Entity.Add<Res>("Assets/Res/Prefabs/Res/Apple.prefab");
        res.RandomRotation = true;
        var r = Random.Range(0.5f, 1f);
        var a = Random.Range(Mathf.PI * 0.5f, Mathf.PI * 1.5f);
        var px = Mathf.Sin(a) * r;
        var pz = Mathf.Cos(a) * r;

        var pos = this.GetWorldPosition() + new Vector3(px, 0f, pz);
        res.Pos = GameEntry.Context.World.MapGrid.GetGroundPosition(pos);
    }
}